package org.nox.helloseries.core.connector.tracker.impl;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.jdom2.Element;
import org.nox.helloseries.core.connector.tracker.AbstractRSSTorrentSearch;
import org.nox.helloseries.domain.NomTracker;
import org.nox.helloseries.domain.Serie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TorrentZapSearch extends AbstractRSSTorrentSearch
{
    private final String BASE_URL = "http://www.torrentzap.com/searchrss/";

    private static final Logger LOG = LoggerFactory.getLogger( TorrentZapSearch.class );

    @Override
    protected int getSeeds( Element e )
    {
        int seeds = -1;
        String desc_tmp = e.getChildText( "description" );
        Properties p = new Properties();
        InputStream input = new ByteArrayInputStream( desc_tmp.getBytes() );
        try
        {
            p.load( input );
        }
        catch ( IOException ex )
        {
            LOG.error( ex.getMessage() );
        }
        String seeds_tmp = p.getProperty( "Seeds" ).split( "\\ " )[0];
        if ( !seeds_tmp.equals( "," ) )
        {
            seeds = Integer.parseInt( seeds_tmp );
        }
        return seeds;
    }

    @Override
    protected double getTailleFichier( Element e )
    {
        return Double.parseDouble( e.getChildText( "size" ) ) / 1024 / 1024;
    }

    @Override
    protected String getTitre( Element e )
    {
        return e.getChildText( "title" );
    }

    @Override
    protected String getUrl( Element e )
    {
        return e.getChild( "enclosure" ).getAttributeValue( "url" );
    }

    @Override
    protected String getUrlRecherche( Serie serie )
    {
        return BASE_URL + ( serie.nextEpisode() ).replaceAll( " ", "%20" );
    }

    @Override
    protected NomTracker getNomTracker()
    {
        return NomTracker.TORRENTZAP;
    }

}
